<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购单号" prop="purchaseNo">
        <el-input v-model="queryParams.purchaseNo" placeholder="请输入采购单号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable size="small">
          <el-option v-for="item in supplierOptions" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单号" align="center" prop="purchaseNo" width="180" />
      <el-table-column label="供应商" align="center" prop="supplierName" width="180" />
      <el-table-column label="采购日期" align="center" prop="purchaseDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计到货日期" align="center" prop="expectedDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" width="120">
        <template slot-scope="scope">
          <span>¥ {{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusType(scope.row.status)">{{ statusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creatorName" width="100" />
      <el-table-column label="审批人" align="center" prop="approvalUserName" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-if="scope.row.status === 0">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-if="scope.row.status === 0">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handleSubmit(scope.row)" v-if="scope.row.status === 0">提交审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-check" @click="handleApprove(scope.row)" v-if="scope.row.status === 1">审批</el-button>
          <el-button size="mini" type="text" icon="el-icon-close" @click="handleReject(scope.row)" v-if="scope.row.status === 1">拒绝</el-button>
          <el-button size="mini" type="text" icon="el-icon-finished" @click="handleReceive(scope.row)" v-if="scope.row.status === 2">入库</el-button>
          <el-button size="mini" type="text" icon="el-icon-finished" @click="handleReceive(scope.row)" v-if="scope.row.status === 3">继续入库</el-button>
          <el-button size="mini" type="text" icon="el-icon-close" @click="handleCancel(scope.row)" v-if="scope.row.status >= 0 && scope.row.status < 3">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购单号" prop="purchaseNo">
              <el-input v-model="form.purchaseNo" placeholder="系统自动生成" :disabled="form.purchaseId !== undefined" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%;" :disabled="form.purchaseId !== undefined && form.status !== 0">
                <el-option v-for="item in supplierOptions" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker v-model="form.purchaseDate" type="date" placeholder="选择采购日期" style="width: 100%;" :disabled="form.purchaseId !== undefined && form.status !== 0" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计到货日期" prop="expectedDate">
              <el-date-picker v-model="form.expectedDate" type="date" placeholder="选择预计到货日期" style="width: 100%;" :disabled="form.purchaseId !== undefined && form.status !== 0" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="form.purchaseId !== undefined && form.status !== 0" />
        </el-form-item>
        <el-form-item label="采购明细" class="mt20">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddItem" v-if="!readonly">添加明细</el-button>
          <el-table :data="form.items" style="width: 100%; margin-top: 10px;">
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="商品" prop="productName" min-width="180">
              <template slot-scope="scope">
                <el-select v-model="scope.row.productId" placeholder="选择商品" style="width: 100%;" :disabled="readonly" @change="(val) => handleProductChange(val, scope.$index)">
                  <el-option v-for="item in productOptions" :key="item.productId" :label="item.productName" :value="item.productId" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="规格" prop="specification" width="100" />
            <el-table-column label="单位" prop="unit" width="80" />
            <el-table-column label="单价" prop="unitPrice" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" :step="0.1" :disabled="readonly" @change="calculateAmount(scope.$index)" />
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" :disabled="readonly" @change="calculateAmount(scope.$index)" />
              </template>
            </el-table-column>
            <el-table-column label="金额" prop="amount" width="120">
              <template slot-scope="scope">
                <span>¥ {{ scope.row.amount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="已入库数量" prop="receivedQuantity" width="120" v-if="form.status >= 3">
              <template slot-scope="scope">
                <span>{{ scope.row.receivedQuantity }} {{ scope.row.unit }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80" v-if="!readonly">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <span style="margin-right: 20px;">总金额: ¥ {{ form.totalAmount }}</span>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!readonly">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 入库对话框 -->
    <el-dialog title="采购入库" :visible.sync="receiveOpen" width="800px" append-to-body>
      <el-form ref="receiveForm" :model="receiveForm" label-width="100px">
        <el-form-item label="采购单号">
          <span>{{ receiveForm.purchaseNo }}</span>
        </el-form-item>
        <el-form-item label="供应商">
          <span>{{ receiveForm.supplierName }}</span>
        </el-form-item>
        <el-form-item label="入库明细">
          <el-table :data="receiveForm.items" style="width: 100%; margin-top: 10px;">
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="商品" prop="productName" min-width="180" />
            <el-table-column label="规格" prop="specification" width="100" />
            <el-table-column label="单位" prop="unit" width="80" />
            <el-table-column label="单价" prop="unitPrice" width="120">
              <template slot-scope="scope">
                <span>¥ {{ scope.row.unitPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="采购数量" prop="quantity" width="100" />
            <el-table-column label="已入库数量" prop="receivedQuantity" width="100" />
            <el-table-column label="本次入库数量" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.receiveQuantity" :min="0" :max="scope.row.quantity - scope.row.receivedQuantity" :precision="0" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="入库仓库">
          <el-select v-model="receiveForm.warehouseId" placeholder="请选择仓库" style="width: 100%;">
            <el-option v-for="item in warehouseOptions" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="receiveForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReceiveForm">确 定</el-button>
        <el-button @click="receiveOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="采购单审批" :visible.sync="approveOpen" width="500px" append-to-body>
      <el-form ref="approveForm" :model="approveForm" label-width="100px">
        <el-form-item label="采购单号">
          <span>{{ approveForm.purchaseNo }}</span>
        </el-form-item>
        <el-form-item label="审批结果">
          <el-radio-group v-model="approveForm.status">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="-1">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="remark">
          <el-input v-model="approveForm.remark" type="textarea" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApproveForm">确 定</el-button>
        <el-button @click="approveOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, getPurchase, addPurchase, updatePurchase, delPurchase, generatePurchaseNo, 
  submitPurchase, approvePurchase, cancelPurchase, receivePurchase } from "@/api/purchase/purchase";
import { listSupplier } from "@/api/supplier/supplier";
import { listProduct } from "@/api/product/product";
import { listWarehouse } from "@/api/inventory/warehouse";

export default {
  name: "Purchase",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单表格数据
      purchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否只读模式
      readonly: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseNo: undefined,
        supplierId: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        purchaseId: undefined,
        purchaseNo: undefined,
        supplierId: undefined,
        totalAmount: 0,
        status: 0,
        purchaseDate: undefined,
        expectedDate: undefined,
        remark: undefined,
        items: []
      },
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        purchaseDate: [
          { required: true, message: "采购日期不能为空", trigger: "blur" }
        ]
      },
      // 供应商选项
      supplierOptions: [],
      // 商品选项
      productOptions: [],
      // 仓库选项
      warehouseOptions: [],
      // 状态选项
      statusOptions: [
        { value: 0, label: "草稿" },
        { value: 1, label: "审核中" },
        { value: 2, label: "已审核" },
        { value: 3, label: "已入库" },
        { value: 4, label: "已完成" },
        { value: -1, label: "已取消" }
      ],
      // 入库对话框
      receiveOpen: false,
      // 入库表单
      receiveForm: {
        purchaseId: undefined,
        purchaseNo: undefined,
        supplierName: undefined,
        warehouseId: undefined,
        remark: undefined,
        items: []
      },
      // 审批对话框
      approveOpen: false,
      // 审批表单
      approveForm: {
        purchaseId: undefined,
        purchaseNo: undefined,
        status: 2,
        remark: undefined
      }
    };
  },
  created() {
    this.getList();
    this.getSupplierOptions();
    this.getProductOptions();
    this.getWarehouseOptions();
  },
  methods: {
    /** 查询采购单列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取供应商选项 */
    getSupplierOptions() {
      listSupplier().then(response => {
        this.supplierOptions = response.data;
      });
    },
    /** 获取商品选项 */
    getProductOptions() {
      listProduct().then(response => {
        this.productOptions = response.data;
      });
    },
    /** 获取仓库选项 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        this.warehouseOptions = response.data;
      });
    },
    // 状态样式
    statusType(status) {
      if (status === -1) return "danger";
      if (status === 0) return "info";
      if (status === 1) return "warning";
      if (status === 2) return "success";
      if (status === 3) return "primary";
      if (status === 4) return "";
      return "info";
    },
    // 状态文字
    statusLabel(status) {
      const option = this.statusOptions.find(item => item.value === status);
      return option ? option.label : "";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: undefined,
        purchaseNo: undefined,
        supplierId: undefined,
        totalAmount: 0,
        status: 0,
        purchaseDate: undefined,
        expectedDate: undefined,
        remark: undefined,
        items: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.readonly = false;
      generatePurchaseNo().then(response => {
        this.form.purchaseNo = response.data;
        this.open = true;
        this.title = "添加采购单";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.readonly = false;
      const purchaseId = row.purchaseId || this.ids[0];
      getPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.form.items = this.form.items || [];
        this.open = true;
        this.title = "修改采购单";
      });
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      this.reset();
      this.readonly = true;
      const purchaseId = row.purchaseId;
      getPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.form.items = this.form.items || [];
        this.open = true;
        this.title = "查看采购单详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查明细是否为空
          if (this.form.items.length === 0) {
            this.$message.warning("请添加采购明细");
            return;
          }

          // 计算总金额
          let totalAmount = 0;
          this.form.items.forEach(item => {
            totalAmount += Number(item.amount);
          });
          this.form.totalAmount = totalAmount;

          if (this.form.purchaseId != undefined) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids;
      this.$modal.confirm('是否确认删除采购单编号为"' + purchaseIds + '"的数据项？').then(function() {
        return delPurchase(purchaseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`);
    },
    /** 添加明细行 */
    handleAddItem() {
      this.form.items.push({
        productId: undefined,
        productName: undefined,
        specification: undefined,
        unit: undefined,
        unitPrice: 0,
        quantity: 1,
        amount: 0,
        receivedQuantity: 0
      });
    },
    /** 删除明细行 */
    handleDeleteItem(index) {
      this.form.items.splice(index, 1);
      this.calculateTotalAmount();
    },
    /** 计算金额 */
    calculateAmount(index) {
      const item = this.form.items[index];
      if (item.unitPrice && item.quantity) {
        item.amount = Number((item.unitPrice * item.quantity).toFixed(2));
        this.calculateTotalAmount();
      }
    },
    /** 计算总金额 */
    calculateTotalAmount() {
      let total = 0;
      this.form.items.forEach(item => {
        total += Number(item.amount || 0);
      });
      this.form.totalAmount = total.toFixed(2);
    },
    /** 选择商品后的处理 */
    handleProductChange(productId, index) {
      const product = this.productOptions.find(p => p.productId === productId);
      if (product) {
        this.form.items[index].productName = product.productName;
        this.form.items[index].specification = product.specification;
        this.form.items[index].unit = product.unit;
        this.form.items[index].unitPrice = product.purchasePrice;
        this.calculateAmount(index);
      }
    },
    /** 提交审核 */
    handleSubmit(row) {
      this.$modal.confirm('确认要提交该采购单进行审核吗？').then(() => {
        return submitPurchase(row.purchaseId);
      }).then(response => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(() => {});
    },
    /** 审批 */
    handleApprove(row) {
      this.approveForm = {
        purchaseId: row.purchaseId,
        purchaseNo: row.purchaseNo,
        status: 2,
        remark: ""
      };
      this.approveOpen = true;
    },
    /** 提交审批 */
    submitApproveForm() {
      approvePurchase(this.approveForm).then(response => {
        this.$modal.msgSuccess("审批成功");
        this.approveOpen = false;
        this.getList();
      });
    },
    /** 拒绝 */
    handleReject(row) {
      this.approveForm = {
        purchaseId: row.purchaseId,
        purchaseNo: row.purchaseNo,
        status: -1,
        remark: ""
      };
      this.approveOpen = true;
    },
    /** 取消采购单 */
    handleCancel(row) {
      this.$modal.confirm('确认要取消该采购单吗？').then(() => {
        return cancelPurchase(row.purchaseId);
      }).then(response => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 入库处理 */
    handleReceive(row) {
      getPurchase(row.purchaseId).then(response => {
        const purchase = response.data;
        // 准备入库表单
        this.receiveForm = {
          purchaseId: purchase.purchaseId,
          purchaseNo: purchase.purchaseNo,
          supplierName: purchase.supplierName,
          warehouseId: 1, // 默认第一个仓库
          remark: "",
          items: []
        };
        
        // 处理明细
        purchase.items.forEach(item => {
          // 只显示未完全入库的商品
          if (item.receivedQuantity < item.quantity) {
            this.receiveForm.items.push({
              itemId: item.itemId,
              productId: item.productId,
              productName: item.productName,
              specification: item.specification,
              unit: item.unit,
              unitPrice: item.unitPrice,
              quantity: item.quantity,
              receivedQuantity: item.receivedQuantity,
              receiveQuantity: item.quantity - item.receivedQuantity // 默认全部入库
            });
          }
        });
        
        // 如果存在需要入库的明细，则打开对话框
        if (this.receiveForm.items.length > 0) {
          this.receiveOpen = true;
        } else {
          this.$modal.msgInfo("该采购单所有商品已完成入库");
        }
      });
    },
    /** 提交入库表单 */
    submitReceiveForm() {
      // 检查入库数量
      const hasReceiveItems = this.receiveForm.items.some(item => item.receiveQuantity > 0);
      if (!hasReceiveItems) {
        this.$message.warning("请至少输入一项入库数量");
        return;
      }
      
      // 过滤出有入库数量的明细
      const receiveItems = this.receiveForm.items
        .filter(item => item.receiveQuantity > 0)
        .map(item => ({
          itemId: item.itemId,
          quantity: item.receiveQuantity
        }));
      
      // 提交入库
      const params = {
        purchaseId: this.receiveForm.purchaseId,
        warehouseId: this.receiveForm.warehouseId,
        remark: this.receiveForm.remark,
        items: receiveItems
      };
      
      receivePurchase(params).then(response => {
        this.$modal.msgSuccess("入库成功");
        this.receiveOpen = false;
        this.getList();
      });
    }
  }
};
</script> 